package com.whfc.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whfc.common.exception.BizException;
import com.whfc.common.result.ResultEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author sun_guodong
 * @description 身份校验
 * @date 2020-06-18
 */
public class IdCardVerifyUtil {
    private static final Logger logger = LoggerFactory.getLogger(IdCardVerifyUtil.class);

    private static final String HOST = "https://edis3p.market.alicloudapi.com";
    private static final String PATH = "/edis_ctid_id_name_image";
    private static final String APP_CODE = "7f4431012872465aaa304631d80f51ba";

    public static boolean idCardVerify(String name, String idCardNo, String imgUrl) {

        if (StringUtils.isEmpty(name)
                || StringUtils.isEmpty(idCardNo)
                || StringUtils.isEmpty(imgUrl)) {
            return false;
        }

        Map<String, String> headers = new HashMap<>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + APP_CODE);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        //防重放校验
        headers.put("X-Ca-Nonce", UUID.randomUUID().toString());
        Map<String, String> bodys = new HashMap<>();
        bodys.put("idCard", idCardNo);
        String image = encodeImageToBase64(imgUrl);
        bodys.put("image", image);
        bodys.put("name", name);
        try {
            String url = HOST + PATH;
            String result = HttpUtil.doPost(url, headers, bodys);
            logger.info("人证对比，response:{}", result);
            JSONObject jsonObject = JSON.parseObject(result);
            String code = jsonObject.getString("code");
            if ("0000".equals(code)) {
                return true;
            }
            logger.warn("人证对比错误,msg:{}", jsonObject.getString("msg"));
        } catch (Exception e) {
            logger.error("人证对比错误,error info:{}", e.getMessage());
        }
        return false;
    }

    /**
     * 将网络图片编码为base64
     *
     * @param imgUrl 图片地址
     * @return img base64编码
     */
    private static String encodeImageToBase64(String imgUrl) {
        try {
            URL url = new URL(imgUrl);
            logger.info("图片的路径为:" + url.toString());
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            inStream.close();
            byte[] data = outStream.toByteArray();

            String base64 = encodeToString(data);

            logger.info("网络文件[{}]编码成base64字符串:[{}]" + url.toString() + base64);
            return base64;
        } catch (IOException e) {
            logger.error("图片base64失败", e);
            throw new BizException(ResultEnum.FAILURE.getCode(), "图片base64失败");
        }
    }

    private static String encodeToString(byte[] data) {
        if (data.length == 0) {
            return "";
        }
        return new String(Base64.getEncoder().encode(data), StandardCharsets.UTF_8);
    }
}
